package com.kuang.bx.controller;

import com.kuang.bx.pojo.Blog;
import com.kuang.bx.pojo.User;
import com.kuang.bx.result.Result;
import com.kuang.bx.result.ResultFactory;
import com.kuang.bx.service.BlogService;
import com.kuang.bx.service.UserService;
import com.kuang.bx.utils.StringUtils;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.HtmlUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;


@RestController
public class BlogController {
    @Autowired
    BlogService blogService;
    UserService userService;
    @CrossOrigin
    @GetMapping("/api/blogs")
    public List<Blog>  list(){
        return blogService.List();
    }

    @CrossOrigin
    @PostMapping("/api/blogs")
    public Blog addOrUpdate(@RequestBody Blog blog){
        blogService.addOrUpdate(blog);
        return blog;
    }

    @CrossOrigin
    @PostMapping("/api/delete")
    public void  delete(@RequestBody Blog blog){
        blogService.deleteAndSortFindBlog(blog.getId());
    }

    @CrossOrigin
    @GetMapping("/api/categories/{cid}/blogs")
    public List<Blog> listByCategory(@PathVariable("cid") int cid) throws Exception{
        if(0 != cid){
            return blogService.listByCategory(cid);
        }else{
            return list();
        }
    }
    @CrossOrigin
    @GetMapping(value = "/api/search")
    public List<Blog> SelectResult(@RequestParam("keywords") String keywords){
        //关键词为空时查询出所有书籍
        if("".equals(keywords)){
            return blogService.List();
        }else{
            return  blogService.Search(keywords);
        }
    }

    @CrossOrigin
    @PostMapping("api/covers")
    public String coversUpload(MultipartFile file) throws Exception {
        String folder = "D:/workspace/img";
        File imageFolder = new File(folder);
        File f = new File(imageFolder, StringUtils.getRandomString(6) + file.getOriginalFilename()
                .substring(file.getOriginalFilename().length() - 4));
        if (!f.getParentFile().exists())
            f.getParentFile().mkdirs();
        try {
            file.transferTo(f);
            String imgURL = "http://localhost:8443/api/file/" + f.getName();
            return imgURL;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

}
